package com.example.leetcode.utils;

import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.MessageDigest;
import java.util.UUID;


public class CryptUtil {

    private static final String MAC_NAME = "HmacSHA256";
    private static final String ENCODING = "UTF-8";
    private static final String MD5 = "md5";

    public static byte[] HmacSHA256Encrypt(String encryptText, String encryptKey) throws Exception {
        MessageDigest md5 = MessageDigest.getInstance(MD5);
        md5.update(encryptKey.getBytes(ENCODING));
        // md5加密
        byte[] data = md5.digest();
        // 根据给定的字节数组构造一个密钥,第二参数指定一个密钥算法的名称
        SecretKey secretKey = new SecretKeySpec(data, MAC_NAME);
        // 生成一个指定 Mac 算法 的 Mac 对象
        Mac mac = Mac.getInstance(MAC_NAME);
        // 用给定密钥初始化 Mac 对象
        mac.init(secretKey);

        // 完成 Mac 操作
        return mac.doFinal(encryptText.getBytes(ENCODING));
    }

    public static String byteArrayToHexString(byte[] b) {
        StringBuilder hs = new StringBuilder();
        String stmp;
        for (int n = 0; b != null && n < b.length; n++) {
            stmp = Integer.toHexString(b[n] & 0XFF);
            if (stmp.length() == 1)
                hs.append('0');
            hs.append(stmp);
        }
        return hs.toString().toUpperCase();
    }

    public static String md5EncryptHmaxSha256(String encryptText, String encryptKey) {
        byte[] bytes = null;
        try {
            bytes = CryptUtil.HmacSHA256Encrypt(encryptText, encryptKey);
        } catch (Exception e) {
        }
        return byteArrayToHexString(bytes).toUpperCase();

    }

    public static void main(String[] args) {
        long l = System.currentTimeMillis()+10000000000L;
        String appId = "1875012064116764673";
        String reqId = String.valueOf(UUID.randomUUID());
        System.out.println(l);
        StringBuffer sb = new StringBuffer("appId=").append(appId).append("&reqId=").append(reqId)
                .append("&timestamp=").append(l);
        String sign = md5EncryptHmaxSha256(sb.toString(), "f235c150-3920-4fb3-9cea-943c88608147");
        System.out.println(sign);
        System.out.println(reqId);
    }


}
